<?php
/**
 * 用户注册Service修改
 * @author hjc
 */
class UserRegisterService extends BaseService
{
    private $mUser;
    private $mUserInfo;
    private $mWechatUser;
    
    public $userBaseData;
    public $userInfoData;
    public $wechatUserData;

    public function _initialize()
    {
        parent::_initialize();
        
        $this->mUser = D('User');
        $this->mUserInfo = D('UserInfo');
        $this->mWechatUser = D('Wechat/WechatUser');
    }
    
    /**
     * 保存用户基础信息
     * @param array $userData   用户数据
     */
    private function saveUserBase($userData)
    {
        if (!$userData) {
            return false;
        }
        
        $res = $this->mUser->update($userData);
        if ($res) {
            session('userId', $res['user_id']);
        }
        
        return $res;
    }
    
    /**
     * 保存微信用户信息
     * @param array $wechatUserInfo 微信用户信息
     */
    public function saveWechatUser($wechatUserInfo)
    {
        if (!$wechatUserInfo) {
            return false;
        }
        $type = isset($wechatUserInfo['is_alipay'])&&$wechatUserInfo['is_alipay'] ? $wechatUserInfo['is_alipay'] : 0;
        if($type == 0){
            return $this->mWechatUser->update($wechatUserInfo);
        }else{
            return M('AlipayUser')->update($wechatUserInfo);
        }
        
    }
    
    /**
     * 保存用户信息
     * @param array $userInfo 用户的辅助信息
     */
    private function saveUserInfo($userInfo)
    {
        if (!$userInfo) {
            return false;
        }
        
        return $this->mUserInfo->update($userInfo);
    }
    
    /**
     * 保存用户信息
     * @param boolen $isAddUserInfo 是否添加用户信息
     * @return boolen
     */
    public function save($isAddUserInfo = false)
    {
        //保存用户基础信息
        $res = $this->saveUserBase($this->userBaseData);
        if (!$res) {
            return false;
        }
        
        //保存用户信息
        $uInfoRes = true;
        if ($isAddUserInfo) {
            $uInfoRes = $this->saveUserInfo($this->userInfoData);
        }
        
        //保存微信用户信息
        if (!$this->wechatUserData['user_id']) {
            $this->wechatUserData['user_id'] = $res['user_id'];
        }
        $wInfoRes = $this->saveWechatUser($this->wechatUserData);
        
        return $res && $uInfoRes && $wInfoRes;
    }
    
    /**
     * 获得用户信息通过用户id
     * @param type $userId
     */
    public function userExists($userId,$accountId)
    {
        $condition = array(
            'user_id' => $userId,
            'status' => array('eq',2),
            'account_id' => $accountId
        );
        $uid = $this->mUser->where($condition)->getField('user_id');

        $res = $uid ? true : false;
        return $res;
    }
}